package com.findviewbydream.evil.eda.Activity;

import android.content.Context;
import android.graphics.Color;
import android.support.design.widget.TextInputEditText;
import android.support.design.widget.TextInputLayout;
import android.support.v7.widget.CardView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.findviewbydream.evil.eda.Bean.ShareBean;
import com.findviewbydream.evil.eda.Data.Data;
import com.findviewbydream.evil.eda.Data.UserData;
import com.findviewbydream.evil.eda.R;
import com.findviewbydream.evil.eda.Utils.Dialog.CallBack;
import com.findviewbydream.evil.eda.Utils.Dialog.CustomMaterialDialog;
import com.findviewbydream.evil.eda.Utils.Dialog.LoadingDialog;
import com.findviewbydream.evil.eda.Utils.NetUtils;
import com.findviewbydream.evil.eda.Utils.Utils;
import com.github.ybq.android.spinkit.SpinKitView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sunfusheng.marqueeview.MarqueeView;
import com.wooplr.spotlight.SpotlightView;
import com.yuyh.easyadapter.recyclerview.EasyRVAdapter;
import com.yuyh.easyadapter.recyclerview.EasyRVHolder;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import cn.iwgang.familiarrecyclerview.FamiliarRecyclerView;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import okhttp3.Call;

/********************************************
 * 工程名：Eda
 * 包名：com.findviewbydream.evil.eda.Activity
 * 时间：16-9-19 下午9:31
 * 作者：白雨濃 evil
 * 邮箱：evilbai@foxmail.com
 * 内容：分享页面
 ********************************************/
public class ShareActivity extends BaseActivity
{
    private ImageView background;
    private LinearLayout wirte;
    private LinearLayout share;
    private CardView cardView;
    private FamiliarRecyclerView recyclerView;
    private CustomMaterialDialog dialog;
    private MarqueeView marqueeView;

    private Adapter adapter;
    private ArrayList<ShareBean.Invitee> list;

    @Override
    public int setContentView()
    {
        return R.layout.share_activity;
    }

    @Override
    public String setToolbarTitle()
    {
        return "用户分享";
    }

    @Override
    public void onCreate()
    {
        initView();
        Utils.Glide(R.drawable.background, background);

        setTopInfo();/*设置顶部信息，填写和分享*/
        setGuilde();/*新手引导*/
        toNetWork();/*网络加载，加载被邀请用户列表*/
    }


    /**
     * 初始化控件
     */
    private void initView()
    {
        background = (ImageView) findViewById(R.id.background);
        wirte = (LinearLayout) findViewById(R.id.wirte);
        share = (LinearLayout) findViewById(R.id.share);
        cardView = (CardView) findViewById(R.id.cardView);
        recyclerView = (FamiliarRecyclerView) findViewById(R.id.recyclerView);
        marqueeView = (MarqueeView) findViewById(R.id.marqueeView);
    }

    /**
     * 新手引导
     */
    private void setGuilde()
    {
        new SpotlightView.Builder(this)
                .introAnimationDuration(400)
                .enableRevalAnimation(true)
                .performClick(true)
                .fadeinTextDuration(400)
                .headingTvColor(Utils.getColor(R.color.p_blue_light))
                .headingTvSize(32)
                .headingTvText("分享")
                .subHeadingTvColor(Color.parseColor("#ffffff"))
                .subHeadingTvSize(16)
                .subHeadingTvText("分享给好友\n您与好友可以同时获得100M流量哦！")
                .maskColor(Color.parseColor("#dc000000"))
                .target(share)
                .lineAnimDuration(400)
                .lineAndArcColor(Utils.getColor(R.color.p_blue_light))
                .dismissOnTouch(true)
                .dismissOnBackPress(true)
                .enableDismissAfterShown(true)
                .usageId("share") //UNIQUE ID
                .setListener(s ->
                        new SpotlightView.Builder(this)
                                .introAnimationDuration(400)
                                .enableRevalAnimation(true)
                                .performClick(true)
                                .fadeinTextDuration(400)
                                .headingTvColor(Utils.getColor(R.color.p_lime))
                                .headingTvSize(32)
                                .headingTvText("填写邀请码")
                                .subHeadingTvColor(Color.parseColor("#ffffff"))
                                .subHeadingTvSize(16)
                                .subHeadingTvText("填写邀请码，次月送流量\n您的邀请码即您的手机号！")
                                .maskColor(Color.parseColor("#dc000000"))
                                .target(wirte)
                                .lineAnimDuration(400)
                                .lineAndArcColor(Utils.getColor(R.color.p_lime))
                                .dismissOnTouch(true)
                                .dismissOnBackPress(true)
                                .enableDismissAfterShown(true)
                                .usageId("write") //UNIQUE ID
                                .show()
                )
                .show();

    }

    /**
     * 设置顶部信息
     * 包含
     * ->填写邀请码
     * ->分享
     */
    private void setTopInfo()
    {
        String ad = "您的邀请码为" + UserData.getUserPhoneNum() + "。\n告诉朋友们，你们同时都可以获得流量哦！（次月）";
        marqueeView.startWithText(ad);

        wirte.setOnClickListener(view -> showWirteDialog());
        share.setOnClickListener(view -> showShare());
    }

    /**
     * 显示填写邀请码的窗口
     */
    private void showWirteDialog()
    {
        dialog = new CustomMaterialDialog(this);
        View layout = View.inflate(this, R.layout.share_invitecode_dialog, null);
        dialog.setContentView(layout).show();

        TextInputLayout textInputLayout = (TextInputLayout) layout.findViewById(R.id.textInputLayout);
        TextInputEditText textInputEditText = (TextInputEditText) layout.findViewById(R.id.textInputEditText);
        SpinKitView loading = (SpinKitView) layout.findViewById(R.id.loading);
        Button submit = (Button) layout.findViewById(R.id.button);

        submit.setOnClickListener(view -> {
            textInputLayout.setErrorEnabled(false);
            if (textInputEditText.length() != 11)
            {
                textInputLayout.setErrorEnabled(true);
                textInputLayout.setError("请输入正确的手机号");
            }
            else
            {
                submit.setText("提交中，请稍后……");
                submit.setClickable(false);
                loading.setVisibility(View.VISIBLE);
                OkHttpUtils.post().url(Data.IP + "ShareServlet")
                        .addParams("type", "wirte")
                        .addParams("phone", UserData.getUserPhoneNum())
                        .addParams("imei", UserData.getUserIMEI())
                        .addParams("inviter_phone", textInputEditText.getText().toString())
                        .build()
                        .execute(new StringCallback()
                        {
                            @Override
                            public void onError(Call call, Exception e, int id)
                            {
                                loading.setVisibility(View.GONE);
                                submit.setClickable(true);
                                submit.setText("提交失败，请重试！");
                            }

                            @Override
                            public void onResponse(String response, int id)
                            {
                                loading.setVisibility(View.GONE);
                                if (response.contains("SUCCESS"))
                                {
                                    dialog.dismiss();
                                    Utils.ToastLong(response.replace("SUCCESS:", ""));
                                }
                                else
                                {
                                    submit.setText("提交失败！");
                                    submit.setError("");
                                    submit.setClickable(true);
                                    textInputLayout.setErrorEnabled(true);
                                    if (response.contains("FAIL:"))
                                        textInputLayout.setError(response.replace("FAIL:", ""));
                                    else if (response.contains("ERROR_OVER"))
                                        textInputLayout.setError(response.replace("ERROR_OVER:", ""));
                                    else if (response.contains("ERROR"))
                                        textInputLayout.setError(response.replace("ERROR:", ""));
                                }
                            }
                        });
            }
        });


    }

    /**
     * 分享
     */
    private void showShare()
    {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

        // 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle("Eda答题送流量啦！");
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl("http://fir.im/evil");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("我在使用Eda易答答题，邯郸移动用户能够赚取流量哦！填写我的手机号，我们都能够获取额外的100M流量呢！！！");
        //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
        oks.setImageUrl(Utils.getNetImg("eda.png"));
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://fir.im/evil");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        //oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://fir.im/evil");

        // 启动分享GUI
        oks.show(this);
    }

    /**
     * 网络加载
     */
    private void toNetWork()
    {
        LoadingDialog.showDialog(this);
        OkHttpUtils.post().url(Data.IP + "ShareServlet")
                .addParams("type", "getList")
                .addParams("phone", UserData.getUserPhoneNum())
                .addParams("imei", UserData.getUserIMEI())
                .build().execute(new StringCallback()
        {
            @Override
            public void onError(Call call, Exception e, int id)
            {
                LoadingDialog.showError(ShareActivity.this, () -> toNetWork());
            }

            @Override
            public void onResponse(String response, int id)
            {
                Utils.Logger(response);
                LoadingDialog.dismissDialog();
                list = new Gson().fromJson(response
                        , new TypeToken<ArrayList<ShareBean.Invitee>>() {}.getType());
                if (list == null || list.size() == 0)
                    findViewById(R.id.null_sign).setVisibility(View.VISIBLE);
                else
                    setRecyclerView();
            }
        });
    }

    /**
     * 设置底部的被邀请人列表
     */
    private void setRecyclerView()
    {
        adapter = new Adapter(this, list, R.layout.share_item);
        recyclerView.setAdapter(adapter);
        TextView textView = new TextView(this);
        textView.setText("被邀请人列表");
        recyclerView.addHeaderView(textView);
    }

    private class Adapter extends EasyRVAdapter<ShareBean.Invitee>
    {
        public Adapter(Context context, List<ShareBean.Invitee> list, int... layoutIds)
        {
            super(context, list, layoutIds);
        }

        @Override
        protected void onBindData(EasyRVHolder viewHolder, int position, ShareBean.Invitee item)
        {
            TextView textView = viewHolder.getView(R.id.textView);
            textView.setText("用户：" + item.getInvitee_phone()
                    + "     加入时间：" +
                    new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss")
                            .format(item.getInvitee_time()));
        }
    }


}
